package com.emuporium.gymrat.android.database;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DatabaseHelper2 extends SQLiteOpenHelper {
	private static final int DATABASE_VERSION = 2;
	private static final String DB_PATH = "/data/data/com.emuporium.gymrat.android/databases/";
	private static final String DB_NAME = "gymratan_gymrat2";
	private Context context;

	public DatabaseHelper2(Context context) {
		super(context, DB_NAME, null, DATABASE_VERSION);
		// TODO Auto-generated constructor stub
		this.context = context;
		Log.e("DBHELPER", "CONSTRUCTOR");

		// SQLiteDatabase s = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME,
		// null,
		// SQLiteDatabase.OPEN_READWRITE);
		// onCreate(s);

	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		Log.e("DBHELPER", "CREATING");
		Log.e("WITH:", db.getPath());
		File dbDir = new File(DB_PATH);
		File dbFile = new File(DB_PATH + DB_NAME);
		if (!dbDir.exists())
			dbDir.mkdir();

		Log.e("DBHELPER", "Copying over db");
		// Open your local db as the input stream
		try {
			InputStream myInput = context.getAssets().open(DB_NAME);
			// InputStream myInput =
			// context.getResources().openRawResource(R.raw.DB_NAME);

			// Open the empty db as the output stream
			OutputStream myOutput = new FileOutputStream(dbFile);

			// transfer bytes from the inputfile to the outputfile
			byte[] buffer = new byte[1024];
			int length;
			while ((length = myInput.read(buffer)) > 0) {
				myOutput.write(buffer, 0, length);
			}

			// Close the streams
			myOutput.flush();
			myOutput.close();
			myInput.close();
		} catch (IOException e) {
			Log.e("IOEXCEPTION", e.getMessage());
			e.printStackTrace();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		Log.e("DBHELPER", "UPDATEATTEMPT");
		onCreate(db);

	}

//	@Override
//	public SQLiteDatabase getWritableDatabase() {
//		return SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null,
//				SQLiteDatabase.OPEN_READWRITE
//						+ SQLiteDatabase.NO_LOCALIZED_COLLATORS);
//	}

}
